//
//  MDHFileConstant.m
//  MDHPT
//
//  Created by 高得华 on 2019/4/27.
//  Copyright © 2019年 高得华. All rights reserved.
//

#import "MDHFileConstant.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+Add.h"
#import "GEdwardInfoController.h"

#if __has_include("MDHPT/MDHPT-Swift.h")
#import "MDHPT/MDHPT-Swift.h"
#else
#import "MDHPT-Swift.h"
#endif

@interface MDHFileConstant ()

///hud
@property (nonatomic, strong) MBProgressHUD * hud;

@end

@interface MDHFileConstant ()

///是否iPad
@property (nonatomic, assign, readwrite) BOOL IS_IPAD;
///是否IS_IPHONE
@property (nonatomic, assign, readwrite) BOOL IS_IPHONE;
///是否IS_IPHONE_4
@property (nonatomic, assign, readwrite) BOOL IS_IPHONE_4;
///是否IS_IPHONE_5
@property (nonatomic, assign, readwrite) BOOL IS_IPHONE_5;
///是否IS_IPHONE_6
@property (nonatomic, assign, readwrite) BOOL IS_IPHONE_6;
///是否IS_IPHONE_6_PLUS
@property (nonatomic, assign, readwrite) BOOL IS_IPHONE_6_PLUS;
///是否IS_IPHONE_X
@property (nonatomic, assign, readwrite) BOOL IS_IPHONE_X;
///是否是iPhone X系列
@property (nonatomic, assign, readwrite) BOOL iPhoneXSeries;
///屏幕尺寸的比例
@property (nonatomic, assign, readwrite) CGFloat kAutoScale;

///底部的安全区域
@property (nonatomic, assign, readwrite) CGFloat kSafeAreaBottom;
///顶部的 状态栏的高度
@property (nonatomic, assign, readwrite) CGFloat kSafeAreaTop;
///导航栏的高度
@property (nonatomic, assign, readwrite) CGFloat kNavBarHeight;
///导航栏+状态栏 的高度
@property (nonatomic, assign, readwrite) CGFloat kNavSafeArea;
///底部的安全区域+TabBar 的高度
@property (nonatomic, assign, readwrite) CGFloat kTabbarSafeArea;
///TabBar 的高度
@property (nonatomic, assign, readwrite) CGFloat kTabbarHeight;

///导航栏的属性 translucent
@property (nonatomic, assign, readwrite) BOOL translucent;
///导航栏 translucent为true时  距离顶部的距离
@property (nonatomic, assign, readwrite) CGFloat kTranslucentTop;
///APP的名称 bundleName
@property (nonatomic, copy, readwrite) NSString * bundleName;
///当前手机系统的版本号
//@property (nonatomic, assign, readwrite) CGFloat deviceSVersion;

@end

@implementation MDHFileConstant
//@synthesize ui = _ui;
@synthesize bundleName = _bundleName;

///APP的名字
- (NSString *)bundleName {
    return [GEdwardInfoController sharedInstance].CFBundleDisplayName;
}

//不能让外部访问，同时放在静态块中的
static MDHFileConstant * instance = nil;

///创建单例
+ (MDHFileConstant *)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone: NULL] init] ;
    });
    return instance;
}
+(id)allocWithZone:(struct _NSZone *)zone {
    return [MDHFileConstant share] ;
}
- (id) copyWithZone:(struct _NSZone *)zone {
    return [MDHFileConstant share];
}
- (instancetype)init {
    if (self = [super init]) {
        
        ///当前手机系统的版本号
        self.deviceSVersion = [UIDevice currentDevice].systemVersion.floatValue;
        
        CGRect bounds   = [[UIScreen mainScreen] bounds];
        CGFloat width1  = bounds.size.width;
        CGFloat height1 = bounds.size.height;
        CGFloat scale = width1/375.0;
        //kMMWAutoScale = scale;
        self.kAutoScale = scale;//(scale < 1.0) ? 1.0:scale;
        self.IS_IPAD = ({UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? 1 : 0;});
        self.IS_IPHONE = [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone;
        self.IS_IPHONE_4 = ((width1 == 320) && (height1 == 480)); //(fabs((double)height1 - (double )480) < DBL_EPSILON);
        self.IS_IPHONE_5 = ((width1 == 320) && (height1 == 568));//(fabs((double)height1 - (double )568) < DBL_EPSILON);
        self.IS_IPHONE_6 = ((width1 == 375) && (height1 == 667));//(fabs((double)height1 - (double )667) < DBL_EPSILON);
        self.IS_IPHONE_6_PLUS = ((width1 == 414) && (height1 == 736));//(fabs((double)height1 - (double )736) < DBL_EPSILON);
        // 判断iPHoneXr 判断iPhoneXs Max
        BOOL is_iPHoneXr_xMax = ((width1 == 414) && (height1 == 896));
        ///判断iPhoneX  判断iPhoneXs
        self.IS_IPHONE_X = is_iPHoneXr_xMax || ((width1 == 375) && (height1 == 812));//(fabs((double)height1 - (double )812) < DBL_EPSILON);
        
        ///iPhone X系列
        self.iPhoneXSeries = false;
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            if (@available(iOS 11.0, *)) {
                self.kSafeAreaBottom = [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom;
                if (self.kSafeAreaBottom > 0) {
                    self.iPhoneXSeries = true;
                }
            }
        }
        self.IS_IPHONE_X = self.iPhoneXSeries;
        
        ///安全区域
        self.kSafeAreaTop = [[UIApplication sharedApplication] statusBarFrame].size.height;//self.IS_IPHONE_X ? 44 : 20;
        //self.kSafeAreaBottom = self.IS_IPHONE_X ? 34 : 0;
        self.kNavBarHeight = 44;
        self.kNavSafeArea = self.kNavBarHeight + self.kSafeAreaTop;
        self.kTabbarHeight = 49;
        self.kTabbarSafeArea = self.kSafeAreaBottom + self.kTabbarHeight;
        
        ///导航栏
        self.translucent = true;
        self.kTranslucentTop = self.translucent ? self.kNavSafeArea:0;
    }
    return self;
}


///回到主线程
+ (void)mainAsyncSafe:(VoidBlock)block {
    if ([NSThread isMainThread]) {
        block();
    }else{
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}

//MARK: - ===== 导航栏 == 左右的按钮 ==
/**
 导航栏按钮 图片的形式
 
 @param image 图片名字 可以传空值即:返回按钮
 @param color 需要修改图片的颜色
 @param left 是否距离左侧
 @param target 谁执行
 @param action 执行的方法
 @return UIButton
 */
+ (MMWDHButton *)navImageButton:(NSString *)image
                          color:(UIColor * _Nullable)color
                           left:(BOOL)left
                         target:(id _Nullable)target
                         action:(SEL _Nullable)action {
    if (image.length <= 0) {
        image = kCommonNavButtonBack;
    }
    return [MDHFileConstant navButton:@"" image:image color:color font:nil left:left target:target action:action];
}

/**
 导航栏按钮 文字的形式
 
 @param title 文字 默认为 确定
 @param color 需要修改图片的颜色
 @param font 字体大小 默认13
 @param left 是否距离左侧
 @param target 谁执行
 @param action 执行的方法
 @return UIButton
 */
+ (MMWDHButton *)navTitleButton:(NSString *)title
                          color:(UIColor *)color
                           font:(UIFont *)font
                           left:(BOOL)left
                         target:(id _Nullable)target
                         action:(SEL _Nullable)action {
    if (title.length <= 0) {
        title = @"确定";//kLocalizedString(@"确定", nil);
    }
    return [MDHFileConstant navButton:title image:@"" color:color font:font left:left target:target action:action];
}

///创建导航栏的Button
+ (MMWDHButton *)navButton:(NSString *)title
                     image:(NSString *)image
                     color:(UIColor *)color
                      font:(UIFont *)font
                      left:(BOOL)left
                    target:(id _Nullable)target
                    action:(SEL _Nullable)action {
    ///按钮
    MMWDHButton * btn = [MMWDHButton new];
    ///按钮大小
    MDHFileConstant * file = [MDHFileConstant share];
    CGFloat scale = kMDHPTAutoScale();
    CGFloat topPath = 4;
    btn.frame = CGRectMake(0, topPath, scale*48, (file.kNavBarHeight-topPath*2));
    
    ///添加方法
    if (action && target) {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    
    ///需要添加文字
    if (title.length > 0) {
        ///颜色为nil则为黑色
        if (color == nil) {
            color = [UIColor blackColor];
        }
        ///文字
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitle:title forState:UIControlStateSelected];
        [btn setTitle:title forState:UIControlStateHighlighted];
        ///颜色
        [btn setTitleColor:color forState:UIControlStateNormal];
        [btn setTitleColor:color forState:UIControlStateSelected];
        [btn setTitleColor:color forState:UIControlStateHighlighted];
        ///字体大小
        if (!font) {
            font = [UIFont systemFontOfSize:15];
        }
        btn.titleLabel.font = font;
        
        ///文本的大小
        CGFloat widthText = [title boundingRectWithSize:CGSizeMake(120, 44) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size.width;
        if (widthText > btn.mh_width) {
            btn.mh_width = widthText;
        }
    }
    
    ///添加图片
    if (image.length > 0) {
        UIImage * ima = [UIImage imageNamed:image];
        ///颜色为nil则为黑色
        if (color) {
            ima = [ima imageByTintColor:color];
        }
        [btn setImage:ima forState:UIControlStateNormal];
        [btn setImage:ima forState:UIControlStateSelected];
        [btn setImage:ima forState:UIControlStateHighlighted];
    }
    
    ///{top, left, bottom, right}
    if (left) {///按钮在左侧
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        //btn.contentEdgeInsets = UIEdgeInsetsMake(0, -8.5, 0, 0);
    }else{///按钮在右侧
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        //btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -12*scale);
    }
    
    
    return btn;
}




//MARK: - ===== AlertView ====== -
void AlertViewShowOne(NSString * message) {
    AlertViewShowOneB(message, nil);
}

///一个确定按钮 带返回值
void AlertViewShowOneB(NSString * message, MVVMWCTCAlertViewBlock _Nullable block) {
    AlertViewShowOneTB(@"提示", message, block);
}

///一个确定按钮 带返回值
void AlertViewShowOneTB(NSString * title, NSString * message, MVVMWCTCAlertViewBlock block) {
    AlertViewShowOneTBD(title, message, @"确定", block);
}

///一个确定按钮 带返回值 自定义名称
void AlertViewShowOneTBD(NSString * title, NSString * message, NSString * determine, MVVMWCTCAlertViewBlock block) {
    [MDHFileConstant mainAsyncSafe:^{
        [LEEAlert alert].config
        .LeeTitle(title)
        .LeeContent(message)
        .LeeAddAction(^(LEEAction *action) {
            action.title = determine;
            action.font = [UIFont systemFontOfSize:15];
            action.titleColor = kColor_MDHTheme();
            action.clickBlock = ^{// 点击事件Block
                if (block != nil) {
                    block(2);
                }
            };
        })
        .LeeQueue(true)
        .LeeShow();
    }];
}

/**
 AlertView弹窗 两个按钮   2:确定 1:取消
 
 @param title 标题
 @param content 提示内容
 @param determine 按钮的名称
 @param block 点击的是哪个按钮   2:确定 1:取消
 */
void AlertViewShowTR(NSString * title, NSString * content, NSString * determine, MVVMWCTCAlertViewBlock block) {
    AlertViewShowT(title, content, determine, true, block);
}

/**
 AlertView弹窗 两个按钮   2:确定 1:取消
 
 @param title 标题
 @param content 提示内容
 @param determine 按钮的名称
 @param right 是不是右侧
 @param block 点击的是哪个按钮   2:确定 1:取消
 */
void AlertViewShowT(NSString * title, NSString * content, NSString * determine, BOOL right, MVVMWCTCAlertViewBlock block) {
    AlertViewShowCD(title, content, @"取消", determine, right, block);
}


/**
 AlertView弹窗 两个按钮   2:确定 1:取消
 
 @param title 标题
 @param content 提示内容
 @param cancle 取消按钮名称
 @param determine 确定
 @param right 是不是右侧
 @param block 点击的是哪个按钮   2:确定 1:取消
 */
void AlertViewShowCD(NSString * title, NSString * content, NSString * cancle, NSString * determine, BOOL right, MVVMWCTCAlertViewBlock block) {
    [MDHFileConstant mainAsyncSafe:^{
        [LEEAlert alert].config
        .LeeTitle(title)
        .LeeContent(content)
        .LeeAddAction(^(LEEAction *action) {
            action.title = right ? cancle:determine;
            action.font = [UIFont systemFontOfSize:15];
            action.titleColor = right ? kColor_MDH666666():kColor_MDHTheme();
            action.clickBlock = ^{// 点击事件Block
                block(right ? 1:2);
            };
        }).LeeAddAction(^(LEEAction *action) {
            action.title = right ? determine:cancle;
            action.font = [UIFont systemFontOfSize:15];
            action.titleColor = right ? kColor_MDHTheme():kColor_MDH666666();
            action.clickBlock = ^{// 点击事件Block
                block(right ? 2:1);
            };
        })
        .LeeQueue(true)
        .LeeShow();
    }];
}


/**
 AlertView弹窗 两个按钮   2:确定 1:取消
 
 @param title 标题
 @param content 提示内容
 @param cancle 取消按钮名称
 @param determine 确定
 @param block 点击的是哪个按钮   2:确定 1:取消
 */
void AlertViewShowCDR(NSString * title, NSString * content, NSString * cancle, NSString * determine, MVVMWCTCAlertViewBlock block) {
    AlertViewShowCD(title, content, cancle, determine, true, block);
}




/**
 AlertView弹窗 两个按钮   2:确定 1:取消
 
 @param content 提示内容
 @param determine 按钮的名称
 @param right 是不是右侧
 @param block 点击的是哪个按钮   2:确定 1:取消
 */
extern void AlertViewShowTwo(NSString * content, NSString * determine, BOOL right, MVVMWCTCAlertViewBlock block) {
    AlertViewShowT(@"提示", content, determine, right, block);
}

/**
 AlertView弹窗 两个按钮   1:确定 2:取消
 
 @param content 提示内容
 @param determine 按钮的名称
 @param block 点击的是哪个按钮   2:确定 1:取消
 */
extern void AlertViewShowR(NSString * content, NSString * determine, MVVMWCTCAlertViewBlock block) {
    AlertViewShowTwo(content, determine, true, block);
}

/**
 AlertView弹窗 带有输入框的   2:确定 1:取消
 
 @param title 标题
 @param content 内容
 @param placeholder textField的提示语
 @param block 点击的是哪个按钮   2:确定 1:取消
 */
void AlertViewShowTextField(NSString * title, NSString * content, NSString * placeholder, MVVMWCTCAlertViewTextBlock block) {
    AlertViewShowTextFieldType(UIKeyboardTypeDefault, title, content, placeholder, block);
}


/**
 AlertView弹窗 带有输入框的   2:确定 1:取消
 
 @param type 文本框的键盘类型
 @param title 标题
 @param content 内容
 @param placeholder textField的提示语
 @param block 点击的是哪个按钮   2:确定 1:取消
 */
extern void AlertViewShowTextFieldType(UIKeyboardType type, NSString * title, NSString * content, NSString * placeholder, MVVMWCTCAlertViewTextBlock block) {
    [MDHFileConstant mainAsyncSafe:^{
        // 使用一个变量接收自定义的输入框对象 以便于在其他位置调用
        __block UITextField * tf = nil;
        [LEEAlert alert].config
        .LeeTitle(title)
        .LeeContent(content)
        .LeeAddTextField(^(UITextField *textField) {
            // 这里可以进行自定义的设置
            textField.placeholder = placeholder;
            textField.textColor = [UIColor blackColor];
            textField.textAlignment = NSTextAlignmentCenter;
            textField.keyboardType  = type;
            textField.font = [UIFont systemFontOfSize:14];
            //[textField becomeFirstResponder];
            tf = textField; //赋值
        }).LeeAddAction(^(LEEAction *action) {
            action.title = @"取消";
            action.font = [UIFont systemFontOfSize:15];
            action.titleColor = kColor_MDH666666();
            action.clickBlock = ^{// 点击事件Block
                [tf resignFirstResponder];
                block(1, @"");
            };
        }).LeeAddAction(^(LEEAction *action) {
            action.title = @"确定";
            action.font = [UIFont systemFontOfSize:15];
            action.titleColor = kColor_MDHTheme();
            action.clickBlock = ^{// 点击事件Block
                block(2, tf.text);
                [tf resignFirstResponder];
            };
        })
        .LeeQueue(true)
        .LeeShow();
    }];
}

/**
 大神取消订单的弹窗
 
 @param title 标题
 @param content 内容
 @param view 第三方视图
 @param block 点击的是哪个按钮   2:确定 1:取消 3:第三个按钮
 */
void AlertViewShowCancleOrder(NSString * title, NSString * content, UIView * view, MVVMWCTCAlertViewBlock block) {
    [MDHFileConstant mainAsyncSafe:^{
        [LEEAlert alert].config
        .LeeTitle(title)
        .LeeContent(content)
        .LeeItemInsets(UIEdgeInsetsMake(8, 4, 8, 4)) // 这个间距范围就是对content设置的
        .LeeAddCustomView(^(LEECustomView *custom) {
            custom.view = view;
            custom.positionType = LEECustomViewPositionTypeCenter;
        })
        .LeeAddAction(^(LEEAction *action) {
            action.title = @"取消";
            action.font = [UIFont systemFontOfSize:15];
            action.titleColor = kColor_MDH666666();
            action.clickBlock = ^{// 点击事件Block
                block(1);
            };
        }).LeeAddAction(^(LEEAction *action) {
            action.title = @"前往";
            action.font = [UIFont systemFontOfSize:15];
            action.titleColor = kColor_MDHTheme();
            action.clickBlock = ^{// 点击事件Block
                block(2);
            };
        }).LeeShow();
    }];
}

/**
 多个按钮的点击事件 两个以上 自带取消按钮
 
 @param title 标题
 @param content 副标题
 @param titles 按钮数组
 @param block 由1依次增加
 */
extern void AlertViewShowMultipleButtons(NSString * title, NSString * content, NSArray <NSString *>* titles, MVVMWCTCAlertViewBlock block) {
    if (titles.count <= 0) {
        return;
    }
    [MDHFileConstant mainAsyncSafe:^{
        void(^blockActionTitleInt)(NSString *title, int index, LEEAction *action) = ^(NSString *title, int index, LEEAction *action) {
            action.title = title;
            action.font = [UIFont systemFontOfSize:17];
            action.titleColor = [UIColor blackColor];//init(r: 200, g: 160, b: 130, a: 1.0)
            action.backgroundColor = [[[UIColor alloc] initWithRed:200/255.0 green:160/255.0 blue:130/255.0 alpha:1.0] colorWithAlphaComponent:0.33333*(titles.count+1-index)];
            if (index > 0) {
                action.clickBlock = ^{// 点击事件Block
                    block(index);
                };
            }
        };
        
        [LEEAlert alert].config
        .LeeTitle(title)
        .LeeContent(content)
        .LeeAddAction(^(LEEAction *action) {
            blockActionTitleInt(titles[0], 1, action);
        })
        .LeeAddAction(^(LEEAction *action) {
            blockActionTitleInt(titles[1], 2, action);
        })
        .LeeAddAction(^(LEEAction *action) {
            blockActionTitleInt(titles[2], 3, action);
        })
        .LeeAddAction(^(LEEAction *action) {
            blockActionTitleInt(@"取消", 0, action);
            action.titleColor = kColor_MDH666666();
            action.backgroundColor = [UIColor whiteColor];
        })
        .LeeQueue(true)
        .LeeShow();
    }];
}

//MARK: - ===== HUD ====== -
void ShowSuccessStatus(NSString *statues){
    [MDHFileConstant mainAsyncSafe:^{
        [MBProgressHUD showMessageWindows:statues];
    }];
}

///两秒之后消失的文本提醒
void ShowHUDMesHidden(NSString * statues, UIView * _Nullable view1) {
    if (statues.length) {
        [MDHFileConstant mainAsyncSafe:^{
            UIView * v = view1;
            if (v == nil) {
                v = [MDHRouter sharedInstance].navigationControllerStack.topViewController.view;
            }
            [MBProgressHUD showMessage:statues toView:v];
        }];
    }else{
        DismissHud(view1);
    }
}
void ShowHUDMesHiddenView(UIView * view1) {
    ShowHUDMesHidden(@"", view1);
}

///只传文本
extern void ShowHUDMesageHiddenView(NSString * statues) {
    ShowHUDMesHidden(statues, nil);
}

///展示在哪个视图上
void ShowHUDMessage(NSString * statues, UIView * view1) {
    UIView * v = view1;
    if (v == nil) {
        v = [MDHRouter sharedInstance].navigationControllerStack.topViewController.view;
    }
    DismissHud(v);
    [MDHFileConstant mainAsyncSafe:^{
        [MBProgressHUD showMessag:statues toView:v];
    }];
}
void ShowHUDMessageView(UIView * _Nullable view1) {
    ShowHUDMessage(@"", view1);
}


void ShowMessage(NSString *statues) {
    [MDHFileConstant mainAsyncSafe:^{
        [MBProgressHUD showMessageWindows:statues];
    }];
}

void ShowErrorStatus(NSString *statues){
    [MDHFileConstant mainAsyncSafe:^{
        [MBProgressHUD showMessageWindows:statues];
    }];
}


void ShowMaskStatus(NSString *statues){
    [MDHFileConstant mainAsyncSafe:^{
        [MBProgressHUD showMessageWindows:statues];
    }];
}

void ShowProgress(CGFloat progress){
    [MDHFileConstant mainAsyncSafe:^{
        //[SVProgressHUD showProgress:progress maskType:SVProgressHUDMaskTypeGradient];
    }];
}

void DismissHud(UIView * _Nullable view1) {
    UIView * v = view1;
    if (v == nil) {
        v = [MDHRouter sharedInstance].navigationControllerStack.topViewController.view;
    }
    if (v == nil) {
        v = [UIApplication sharedApplication].keyWindow;
    }
    [MDHFileConstant mainAsyncSafe:^{
        [MBProgressHUD hideHUDForView:v animated:true];
    }];
}



#pragma mark - ===== HUD ===== -
///有进度条的hud
- (void)showMBProgressHUD:(double)complete {
    [self showMBProgressHUD:complete toView:nil];
}
///有进度条的hud
- (void)showMBProgressHUD:(double)complete toView:(UIView *)view {
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete >= 1.0) {
                [self.hud hide:true];
            }
            self.hud.progress = complete;
            
        });
    }else{
        if (complete >= 1.0) {
            [self.hud hide:true];
        }
        self.hud.progress = complete;
    }
}

/// - =====  ==== -
- (MBProgressHUD *)hud {
    if (_hud) {
        return _hud;
    }
    _hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:true];
    _hud.detailsLabelText = @"正在努力奋斗中...";
    //圆饼图
    _hud.mode = MBProgressHUDModeDeterminate;
    // 隐藏时候从父控件中移除
    _hud.removeFromSuperViewOnHide = YES;
    return _hud;
}


@end
